package org.springblade.task.job.report.book;

import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springblade.common.enums.DictBizEnum;
import org.springblade.common.utils.DateUtils;
import org.springblade.modules.booksAnalysis.entity.DailySearchRankingReport;
import org.springblade.modules.booksAnalysis.service.IDailySearchRankingReportService;
import org.springblade.modules.booksAnalysis.vo.DailySearchRankingReportVO;
import org.springblade.task.base.param.BaseOrderBookParam;
import org.springblade.task.base.param.BaseUserClickLogParam;
import org.springblade.task.base.service.IBaseAudioChapterOrderService;
import org.springblade.task.base.service.IBaseEbookOrderService;
import org.springblade.task.base.service.IBaseNetChapterOrderService;
import org.springblade.task.base.service.IBaseUserClickLogService;
import org.springblade.task.base.vo.BaseAudioChapterOrderVO;
import org.springblade.task.base.vo.BaseEbookOrderVO;
import org.springblade.task.base.vo.BaseNetChapterOrderVO;
import org.springblade.task.base.vo.BaseUserClickLogVO;
import org.springblade.task.job.base.BaseTaskInfoJob;
import org.springblade.task.quartz.entity.QuartzTask;
import org.springblade.task.quartz.service.IQuartzTaskService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @Title: 收索排行
 * @version V1.0
 */
@Component
public class DailySearchRankingReportJob {

	private static Logger logger = LoggerFactory.getLogger(BaseTaskInfoJob.class);
	@Autowired
	private IBaseUserClickLogService baseUserClickLogService;
	@Autowired
	private IBaseEbookOrderService baseEbookOrderService;
	@Autowired
	private IBaseNetChapterOrderService baseNetChapterOrderService;
	@Autowired
	private IBaseAudioChapterOrderService baseAudioChapterOrderService;

	@Autowired
	private IDailySearchRankingReportService dailySearchRankingReportService;

	@Autowired
	private IQuartzTaskService quartzTaskService;

	/**
	 * 1、简单任务示例（Bean模式）
	 */
	@XxlJob("dailySearchRankingReportJob")
	public ReturnT<String> dailySearchRankingReportJob(String param) throws Exception {
		System.out.println(DateUtils.currentDateTime() + " -- XXL-JOB, Hello World.");
		System.err.println("执行静态定时任务日期: " + DailySearchRankingReportJob.class.getSimpleName());
		QuartzTask quartzTask = quartzTaskService.queryByTaskName(DailySearchRankingReportJob.class.getSimpleName(), -7);
		// 今日
		String todayDate = DateUtils.crutDate();
		String taskDate = quartzTask.getTaskDate();
		while (taskDate.compareTo(todayDate) < 0) {
			// 当时间大于5点，跳出执行
//			if (DateUtils.getHour24() > 5) {
//				break;
//			}
			// 再加一个凌晨1点判断
			currMethod(taskDate);
			// 增加1天
			taskDate = DateUtils.dateAddDay(taskDate, 1);
		}
		quartzTask.setTaskDate(taskDate);
		quartzTaskService.saveQuartzTask(quartzTask);
		return ReturnT.SUCCESS;
	}

	/**
	 *
	 * @param taskDate
	 */
	public void currMethod(String taskDate) {

		String startTime = DateUtils.getDateStartTime(taskDate);
		String endTime = DateUtils.getDayEndTime(taskDate);

		BaseUserClickLogParam logParam = new BaseUserClickLogParam();
		logParam.setStartDate(startTime);
		logParam.setEndDate(endTime);
		List<BaseUserClickLogVO> userClickLogVOList = baseUserClickLogService.queryUserClickLogBookList(logParam);

		Map<String, DailySearchRankingReportVO> searchRankingReportMap = new HashMap<>();
		DailySearchRankingReportVO reportVO = null;
		for (BaseUserClickLogVO clickLogVO : userClickLogVOList) {
			String tid = clickLogVO.getTid();
			reportVO = searchRankingReportMap.get(tid);
			if (null == reportVO) {
				reportVO = new DailySearchRankingReportVO();
			}
			String pin = clickLogVO.getPin();
			// 点击搜索
			if (DictBizEnum.CLICK_TYPE_CLICK_SEARCH.getValue() == clickLogVO.getClickType()) {
				reportVO.setKeyWord(clickLogVO.getResName()); // 关键词
				reportVO.setSearchNum(reportVO.getSearchNum() + 1); // 搜索次数
				reportVO.setSearchClickNum(reportVO.getSearchClickNum() + 1); // 搜索点击次数
				Set<String> searchClickUser = reportVO.getSearchClickUser();
				if(searchClickUser == null) {
					searchClickUser = new HashSet<>();
				}
				searchClickUser.add(pin);
				reportVO.setSearchClickUserNum(searchClickUser.size()); // 搜索点击人数
			}
			// vip阅读 \ 立即阅读
			if (DictBizEnum.CLICK_TYPE_VIP_READING.getValue() == clickLogVO.getClickType() || DictBizEnum.CLICK_TYPE_READ_NOW.getValue() == clickLogVO.getClickType()) {
				reportVO.setIntroductionOfReadNum(reportVO.getIntroductionOfReadNum() + 1);// 引入阅读次数
			}
			//  加购
			if (DictBizEnum.CLICK_TYPE_ADDITIONAL_PURCHASE.getValue() == clickLogVO.getClickType()) {
				reportVO.setIntroductionOfPurchaseNum(reportVO.getIntroductionOfPurchaseNum() + 1); // 引入加购数量
			}
			// 点击购买
			if (DictBizEnum.CLICK_TYPE_CLICK_TO_BUY.getValue() == clickLogVO.getClickType()) {

				reportVO.setIntroductionOfPaymentOrderNum(reportVO.getIntroductionOfPaymentOrderNum() +1);
				Set<Long> orderIdSet = reportVO.getOrderIdSet();
				if(orderIdSet == null) {
					orderIdSet = new HashSet<>();
				}
				orderIdSet.add(clickLogVO.getResId()); // 订单ID

				Set<String> paymentUser = reportVO.getPaymentUser();
				if(paymentUser == null) {
					paymentUser = new HashSet<>();
				}
				paymentUser.add(pin); // 付费用户
				reportVO.setIntroductionOfPaymentUserNum(paymentUser.size()); // 引入付费用户数
			}
		}

		BaseOrderBookParam orderParam = new BaseOrderBookParam();
		orderParam.setStartDate(startTime);
		orderParam.setEndDate(endTime);
		List<BaseEbookOrderVO> ebookOrderVOList = baseEbookOrderService.queryDailyOrderList(orderParam);
		// 网文订单
		List<BaseNetChapterOrderVO> netChapterOrderVOList = baseNetChapterOrderService.queryDailyOrderList(orderParam);
		// 有声订单
		List<BaseAudioChapterOrderVO> audioChapterOrderVOList = baseAudioChapterOrderService.queryDailyOrderList(orderParam);

		//
		Iterator iterator = searchRankingReportMap.keySet().iterator();
		List<DailySearchRankingReport> reportList = new ArrayList<>();
		DailySearchRankingReport rankingReport = null;
		while (iterator.hasNext()) {
			String key = iterator.next().toString();
			DailySearchRankingReportVO vo = searchRankingReportMap.get(key);
			Set<Long> orderIdSet = vo.getOrderIdSet();
			rankingReport = new DailySearchRankingReport();
			BeanUtils.copyProperties(vo, rankingReport);
			for(BaseEbookOrderVO orderVO: ebookOrderVOList) {
				if(orderIdSet.contains(orderVO.getOrderId())) {
					// 引入付费金额
					rankingReport.setIntroductionOfOrderAmount(rankingReport.getIntroductionOfOrderAmount() + orderVO.getPayAmount());
				}
			}

			for(BaseNetChapterOrderVO orderVO: netChapterOrderVOList) {
				if(orderIdSet.contains(orderVO.getOrderId())) {
					// 引入付费金额
					rankingReport.setIntroductionOfOrderAmount(rankingReport.getIntroductionOfOrderAmount() + orderVO.getOnlineAmount());
				}
			}

			for(BaseAudioChapterOrderVO orderVO: audioChapterOrderVOList) {
				if(orderIdSet.contains(orderVO.getOrderId())) {
					// 引入付费金额
					rankingReport.setIntroductionOfOrderAmount(rankingReport.getIntroductionOfOrderAmount() + orderVO.getOnlineAmount());
				}
			}

			reportList.add(rankingReport);
		}
		dailySearchRankingReportService.saveBatch(reportList);
	}


	public void init() {
		logger.info("init");
	}

	public void destroy() {
		logger.info("destory");
	}

}
